<template>
  <div class="app-container">
    <search-box :isMulti="false">
      <template slot="content">
        <div class="left-box">
          <el-form-item label="用户姓名">
            <el-input v-model="listQuery.userName"
                      placeholder="请输入"
                      clearable/>
          </el-form-item>

          <el-form-item label="部门名称">
            <el-select v-model="listQuery.departmentName"
                       placeholder="请选择部门">
              <el-option v-for="item in departmentList"
                         :key="item.departmentName"
                         :label="item.departmentName"
                         :value="item.departmentName">
              </el-option>
            </el-select>
          </el-form-item>

        </div>
        <div class="right-box">
          <el-button size="mini"
                     @click="handleFilter">查询
          </el-button>
          <el-button size="mini"
                     @click="reset" type="info">重置
          </el-button>

        </div>
      </template>
    </search-box>
    <div class="table-wrap">

      <div v-for="item in list" style="width: 100%;">
          <div style="font-size: 18px;font-weight: 600;margin-top: 20px">
            {{ item.departmentCode }}-{{ item.departmentName }}
          </div>
        <div v-if="item.userList!=null" style="display: flex;flex-direction: row;margin-left: 2%">
          <div v-for="user in item.userList" style="margin-top: 1%;width: 12%;margin-left: 2%" >
            <div style="float: left;background-color: #E0E0E0;width: 100%;padding: 10px;text-align: center;border-radius: 10px;">
              <img src="../../../assets/images/logo.png" alt="" class="logoImgHeader"/><br><br>
              姓名：{{user.userName}}<br>
              部门：{{user.departmentName}}<br>
              职务：{{user.position}}<br>
              职级：{{user.userRank}}<br>
            </div>
          </div>
        </div>



      </div>

    </div>

  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import * as apiUser from '@/api/user'
  import * as department from '@/api/system-setting/department'
  import * as user from '@/api/system-setting/user'
  import * as rank from '@/api/system-setting/rank'
  import waves from '@/directive/waves' // waves directive
  import Pagination from '@/components/Pagination' // secondary package based on el-pagination
  // 当然你也可以为了方便使用，将它注册到全局
  import { MessageBox } from 'element-ui'
  import bus from '@/utils/eventBus'
  import searchBox from '@/components/searchBox.vue'
  import * as position from '@/api/system-setting/position'
  export default {
    name: 'user',
    components: { Pagination, searchBox },
    directives: { waves },
    filters: {},
    data() {
      return {
        list: null,
        total: 0,
        dialogVisible: false,
        listQuery: { // 查询列表时的参数对象
          pageNumber: 1,
          departmentName: '',
          departmentCode: '',
          roleName: '',
          pageSize: 50,
          name: undefined,
          appName: process.env.VUE_APP_APP_NAME,
          tenantIdList: []
        },
        dialogTitle: '',
        rulesList: [
        ],
        departmentList: [
        ],
        rankList: [
        ],
        positionList: [
        ],
        genderList: [
          {label:'男',value:'男'},
          {label:'女',value:'女'},
          {label:'其他',value:'其他'},
        ],
        rules: {
          departmentName: [{ required: true, message: '部门名称必填', trigger: 'blur' }],
          gender: [{ required: true, message: '性别必选', trigger: 'blur' }],
          roleName: [{ required: true, message: '权限必选', trigger: 'blur' }],
          userCode: [{ required: true, message: '工号不能为空', trigger: 'blur' }],
          userName: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
          birth: [{ required: true, message: '出生日期必选', trigger: 'blur' }],
          idCard: [{ required: true, message: '身份证号不能为空', trigger: 'blur' }],
          position: [{ required: true, message: '职务不能为空', trigger: 'blur' }],
          userAccount: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
        }
      }
    },
    computed: {
      ...mapGetters([
        'selectedTenantId',
        'tenantList'
      ])
    },
    created() {
      this.getList()
      this.getDepartmentList()
      this.getRoleList()
      this.getPostList()
      // 监听 租户改变的事件,选择不同租户后,立马刷新数据
      bus.$on('selectedTenantIdChanged', () => {
        console.log('selectedTenantIdChanged事件触发...')
        this.getList()
      })

    },
    mounted() {
      // 测试用
      // var that = this
      // setTimeout(function() {
      //   that.dialogFormVisible = true
      // }, 5000)

      // alert(this.$store.getters.selectedTenantId);
    },
    beforeDestroy() { // 当路由切换到其他页面时触发
      bus.$off('selectedTenantIdChanged')
    },
    methods: {
      async getList() { // 获取列表数据
        this.listQuery.tenantIdList = []
        if (this.selectedTenantId == undefined) {//当前选中所有的租户
          this.tenantList.forEach((tenant, index) => {
            this.listQuery.tenantIdList.push(tenant.id)
          })
        } else {
          this.listQuery.tenantIdList.push(this.selectedTenantId)
        }
        const { content } = await user.getUserListByDepartment(this.listQuery)
        this.list = content
        console.log('this.list',this.list)

      },

      async getDepartmentList() { // 获取列表数据

        const { content } = await department.getDepartmentList(this.listQuery)
        this.departmentList = content.list;

      },


      async getPostList() { // 获取列表数据
        const { content } = await rank.getRankList(this.listQuery)
        this.rankList = content.list;
      },


      async getPositionList() { // 获取列表数据
        this.positionList = []
        this.listQuery.position = ''
        const { content } = await position.getPositionList(this.listQuery)
        this.positionList = content.list

      },
      async getRoleList() { // 获取列表数据

        const { content } = await department.getRoleList(this.listQuery)
        this.rulesList = content.list;

      },
      handleFilter() {
        this.listQuery.pageNumber = 1
        this.getList()
      },

      handleCreate() {
        this.dialogVisible = true
        this.dialogTitle = '用户新增'
        this.listQuery = {};
        // this.getPositionList()
      },
      handleUpdate(row) {
        this.dialogVisible = true
        this.dialogTitle = '用户编辑'
        this.listQuery = row;
        // this.getPositionList()

      },

      handleDelete(row) {
        this.$confirm('是否删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          user.deleteUser(row.id).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }).catch(() => {
        })

      },

      reset() {
        this.listQuery.userName = ''
        this.listQuery.departmentName = ''
        this.getList()
      },
      cancel() {
        this.listQuery.userName = ''
        this.listQuery.departmentName = ''
        this.dialogVisible = false;
        this.getList()
      },
      onSubmit(){
        this.$refs['form'].validate((valid) => {
          if (valid) {
            this.listQuery.tenantId = this.$store.getters.selectedTenantId
            if(this.dialogTitle=='用户新增'){
              user.createUser(this.listQuery).then((res) => {
                console.log(res);
                if(res.status==200){
                  if(res.content!=null){
                    this.$notify({
                      title: '成功',
                      message: '添加成功',
                      type: 'success',
                      duration: 2000
                    });
                    this.listQuery.userName = ''
                    this.listQuery.departmentName = ''
                    this.dialogVisible = false
                    this.getList();
                  }else{
                    this.$notify({
                      title: '失败',
                      message: '用户名已经被占用！',
                      type: 'error',
                      duration: 2000
                    });
                  }


                }
              })
            }else if(this.dialogTitle=='用户编辑'){
              user.updateUser(this.listQuery).then((res) => {
                console.log(res);
                if(res.status==200){
                  this.$notify({
                    title: '成功',
                    message: '修改成功',
                    type: 'success',
                    duration: 2000
                  });
                  this.listQuery.userName = ''
                  this.listQuery.departmentName = ''
                  this.dialogVisible = false
                  this.getList();

                }
              })
            }

          } else {
            console.log('error submit!!');
            return false;
          }
        });

      }



    }
  }
</script>

<style scoped>
  .app-select {
    margin-bottom: 20px;
  }
  .logoImgHeader {
    width: 100px;
    height: 120px;
    margin-top: 0.5%;

  }
</style>
